//
//  DiarysView.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/25.
//

import SwiftUI


struct DiarysView: View {
    var diarys: [DiaryModel] = DiaryModel.debugDatas
   
    @Environment(\.modelContext) var modelContext
    @State var selectedCategory: CategoryModel?
    @State var selectedCategoryId: UUID = noSelectedId
    @State var diaryByCategory:[DiaryModel] = []
    var body: some View {
       
        List{
            CategoryPickerView(categorys: CategoryModel.debugDatas, selectedCategory: $selectedCategory)
            ForEach(diaryByCategory){ diary in
               
                    DiarysItemView(diary: diary)
                
                    
            }.onDelete(perform: { indexSet in
                for index in indexSet{
                    modelContext.delete(diaryByCategory[index])
                }
            })
            .listRowBackground(Color("back"))
            
            
        }
        .onChange(of: selectedCategory, { _, _ in
            categoryDiarys()
        })
        .onAppear(perform: {
            categoryDiarys()
        })
        .listSectionSeparator(.hidden)
        .scrollContentBackground(.hidden)
        .background(Color("back"))
        .listStyle(.inset)
    }
    private func categoryDiarys(){
        print(self.selectedCategory?.id ?? "no")
        if self.selectedCategory == nil{
            diaryByCategory = diarys.sorted(by: { $0.createDate > $1.createDate })
        }else{
            print("filter")
            diaryByCategory = diarys.filter({ $0.category == self.selectedCategory! }).sorted(by: { $0.createDate > $1.createDate })
        }
    }
}

#Preview {
    DiarysView()
}
